<template>
  <BasicLayout>
    <template #wrapper>
      <table-pagination
        class="table"
        :loading="loading"
        :columns="columns"
        :data="tableData"
        :pagination-show="false"
        border
      >
        <template slot="undoneRegionQuantity" slot-scope="scope">
          <span v-if="scope.item.undoneRegionQuantity===0">{{ scope.item.undoneRegionQuantity }}</span>
          <el-link v-else type="primary" :underline="false" @click="handleShow(scope.item)">{{ scope.item.undoneRegionQuantity }}</el-link>
        </template>
        <template slot="operate" slot-scope="scope">
          <span v-for="button in scope.item.newOpreateOptions" :key="button.name">
            <elink-loading v-if="button.textLoading" :style="{'margin-left': '10px'}" :name="button.name" :index="textNameIndex+''" :text-loading="textName+scope.$index" @clickDown="textNameIndex=scope.$index;button.handleEvent?button.handleEvent(scope.item,button.name):''" />
            <el-link
              v-if="!button.textLoading"
              type="primary"
              :underline="false"
              :style="{'margin-left': '10px'}"
              @click="button.handleEvent?button.handleEvent(scope.item,button.name):''"
            >
              {{ button.name }}
            </el-link>
          </span>
        </template>
      </table-pagination>
      <entry-date :date="date" :visible="dialogDateVisible" @close="dialogDateVisible=false" @submit="onGetEliChecklist" />
      <table-dialog title="未完成大区列表" :columns="[{ prop: 'name', label: '大区名称' }]" :data="undoneRegionsData" :visible="dialogTableVisible" @close="dialogTableVisible=false" />
      <!-- <import-file :date="date" :import-type="importType" :visible="dialogImportVisible" @close="dialogImportVisible=false" @complete="onGetEliChecklist" /> -->
      <import-file
        ref="importFileRef"
        :visible="dialogImportVisible"
        :width="'800px'"
        :error-columns="errorColumns"
        @close="dialogImportVisible = false"
        @downLoadTemplateFile="downLoadTemplateFile"
        @firstImport="firstImport"
        @isImport="isImport"
        @getErrorPage="getErrorList"
        @downLoadErrorFileData="downLoadErrorFileData"
      />
    </template>
  </BasicLayout>
</template>
<script>
import TablePagination from '@/components/common/TablePagination';
import TableDialog from '../tableDialog';
import EntryDate from './entryDate.vue';
import ImportFile from '@/components/common/ImportFile';
import ElinkLoading from './elinkLoading.vue';
import { getEliChecklist, exportComEliChecklist, exportComEliTable, skip, calculate, rollback, whiteBlackList, confirmImport, downloadTemplate, exportErrorData, getErrorPage } from '@/api/replacementApi';
import { judgeResponseType } from '@/utils/tools';
import { exportFile } from '@/utils/tools';
import config from './config';

export default {
  name: 'Headquarters',
  components: {
    TablePagination,
    TableDialog,
    EntryDate,
    ImportFile,
    ElinkLoading
  },
  data() {
    return {
      columns: config.columns,
      errorColumns: config.errorColumns,
      tableData: [],
      opreateOptions: [
        { name: '导入白名单', handleEvent: this.handleImport, show: [1] },
        { name: '导入黑名单', handleEvent: this.handleImport, show: [2] },
        { name: '录入', handleEvent: this.handleInput, show: [4] },
        { name: '跳过', handleEvent: this.handleJumpOver, show: [1, 2, 16], textLoading: true },
        { name: '开始', handleEvent: this.handleStart, show: [8] },
        { name: '-', show: [256] },
        { name: '查看报表', handleEvent: this.handleView, show: [128] },
        { name: '导出汰换商品清单', handleEvent: this.handleExport, show: [128], textLoading: true },
        { name: '导出底表', handleEvent: this.handleExportComEliTable, show: [128], textLoading: true }
        // { name: '操作回滚(前端自测使用)', handleEvent: this.handleRollback, show: [1, 2, 4, 8, 16], textLoading: true }
      ],
      state: [
        { name: '待导入白名单', state: 1 },
        { name: '待导入黑名单', state: 2 },
        { name: '待录入新店日期', state: 4 },
        { name: '待运营开始', state: 8 },
        { name: '审批中', state: 16 },
        { name: '完成', state: 128 },
        { name: '汰换清单计算中', state: 256 }
      ],
      loading: false,
      dialogTableVisible: false,
      dialogDateVisible: false,
      dialogImportVisible: false,
      undoneRegionsData: [], // 未完成大区列表
      date: '',
      importType: null,
      textName: '', // 显示loading的操作栏名称
      textNameIndex: ''
    };
  },
  mounted() {
    this.onGetEliChecklist();
  },
  methods: {
    // 获取汰换清单列表信息
    onGetEliChecklist() {
      this.loading = true;
      getEliChecklist({
        eliReportMode: 'HEADQUARTER'
      }).then(({ data }) => {
        this.loading = false;
        this.tableData = data;
        this.tableData = this.tableData.map(item => {
          // 处理操作栏显示
          const newOpreateOptions = this.opreateOptions.filter(i => i.show.indexOf(item.state) > -1);
          // 处理状态显示
          const newStatus = this.state.filter(i => item.state === i.state);
          // 处理月份显示
          const dateString = new Date(item.date);
          item.month = `${dateString.getFullYear()}年${dateString.getMonth() + 1}月`;
          item.newOpreateOptions = newOpreateOptions;
          item.status = newStatus[0].name;
          return item;
        });
      }).catch(() => {
        this.loading = false;
      });
    },
    // 弹窗展示未完成大区列表信息
    handleShow(item) {
      this.dialogTableVisible = true;
      this.undoneRegionsData = item.undoneRegions.map(item => { return { name: item }; });
    },
    // 录入
    handleInput(item) {
      this.date = item.date;
      this.dialogDateVisible = true;
    },
    // 跳过
    handleJumpOver(item, name) {
      this.textName = name;
      const info = item.state === 16 ? '确认要跳过审批吗？' : `确认要开始跳过导入${item.state === 1 ? '白' : '黑'}名单？跳过之后不可撤销哦`;
      this.$alert(info, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        showCancelButton: true
      }).then(() => {
        skip({ date: item.date }).then(res => {
          this.onGetEliChecklist();
          this.$message.success('已跳过!');
          this.textName = '';
        }).catch(() => { this.textName = ''; });
      }).catch(() => { this.textName = ''; });
    },
    // 开始
    handleStart(item) {
      this.$alert('确认要开始执行上个月份的汰换清单处理逻辑吗？开始之后不可撤销哦', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        showCancelButton: true
      }).then(() => {
        calculate({ date: item.date }).then(({ data }) => {
          this.$message.success('已执行！');
          this.onGetEliChecklist();
        });
      });
    },
    // 查看报表
    handleView(item) {
      this.$router.push({ name: 'eliminatedHeadquartersDetail', params: { date: this.CryptoJS.AES.encrypt(item.date, 'date').toString() }});
    },
    // 导入
    handleImport(item) {
      this.date = item.date;
      this.importType = item.state * 1 === 1 ? 'whitelist' : 'blacklist';
      this.dialogImportVisible = true;
    },
    // 获取导入不合格的商品列表 分页
    getErrorList({ current, size }) {
      getErrorPage({ current, size }).then(res => {
        this.$refs.importFileRef.setErrorTableData(
          current,
          res.data
        );
      });
    },
    // 下载错误数据
    downLoadErrorFileData() {
      exportErrorData().then(res => {
        judgeResponseType(res).then(() => {
          // 说明是正常的文件流
          exportFile(res, '错误数据.xlsx');
        }).catch(error => {
          this.$message.error(error.resultMessage || '请求异常');
        });
      });
    },
    // 下载商品信息导入模板
    downLoadTemplateFile() {
      downloadTemplate().then(res => {
        judgeResponseType(res).then(() => {
          // 说明是正常的文件流
          exportFile(res, '导入模板.xlsx');
        }).catch(error => {
          this.$message.error(error.resultMessage || '请求异常');
        });
      });
    },
    // 重新上传 或者 确认导入
    isImport(proceed) {
      // 确认导入
      confirmImport({ date: this.date, proceed }).then(res => {
        if (!proceed) {
          // 重新上传
          this.$refs.importFileRef.resetData();
          this.$refs.importFileRef.resetStatus();
          return false;
        }
        this.$refs.importFileRef.toThird(res.data || 0);
        this.onGetEliChecklist();
      }).catch(() => {
        this.$refs.importFileRef.resetData();
      }).finally(() => {
        this.$refs.importFileRef.resetStatus();
      });
    },
    // 导入文件后台解析 点击下一步触发
    firstImport(formData) {
      formData.append('date', this.moment(this.date).format('YYYY/MM/DD'));
      whiteBlackList(this.importType, formData, this.$refs.importFileRef.onUploadProgress).then(res => {
        this.fileData = formData;
        this.$refs.importFileRef.toSecond({
          errorNum: res.data.errorNum,
          correctNum: res.data.correctNum
        });
        if (res.data.errorNum > 0) {
          // 获取错误数据列表
          this.getErrorList({
            current: 1,
            size: 10
          });
        }
      }).catch(() => {
        this.$refs.importFileRef.resetProgress();
      });
    },
    // 导出商品汰换清单
    handleExport(item, name) {
      this.textName = name;
      exportComEliChecklist({
        date: item.date,
        eliReportMode: 'HEADQUARTER'
      }).then(res => {
        this.blobDataJudgement(res, `${item.month}汰换商品清单.xlsx`);
      }).catch(() => { this.textName = ''; });
    },
    // 导出底表
    handleExportComEliTable(item, name) {
      this.textName = name;
      exportComEliTable({
        date: item.date,
        eliReportMode: 'HEADQUARTER'
      }).then(res => {
        this.blobDataJudgement(res, `${item.month}底表.xlsx`);
      }).catch(() => { this.textName = ''; });
    },
    // 二进制文件流返回错误判断
    blobDataJudgement(res, fileName) {
      if (res.type === 'application/json') {
        // 说明是普通对象数据，后台转换失败
        const reader = new FileReader();
        reader.readAsText(res, 'utf-8');
        reader.onload = () => {
          const jsonData = JSON.parse(reader.result);
          this.$message.error(jsonData.resultMessage);
        };
      } else {
        exportFile(res, fileName);
        this.$message.success('报表文件已生完毕, 下载中，请稍后');
      }
      this.textName = '';
    },
    // 操作回滚
    handleRollback(item, name) {
      this.textName = name;
      rollback({
        date: item.date
      }).then(res => {
        this.textName = '';
        this.onGetEliChecklist();
      }).catch(() => { this.textName = ''; });
    }
  }
};
</script>

<style lang="scss" scoped>
.table{
  margin: 20px 0;
  ::v-deep .el-link--inner{
    position: relative;
    .text{
      color: rgba(64, 158, 255, 0.2);
    }
    .el-icon-loading{
      position: absolute;
      top: 4px;
      left: 50%;
      margin-left: -9px;
    }
    .el-progress{
      position: absolute;
      top: 2px;
      left: 0;
      width: 100%;

    }
  }
}
</style>
